import type { Ref } from 'vue'
import { reactive, toRefs, ref, unref, nextTick } from 'vue'

type useTableOptions<T> = {
  formatResult?: (data: T[]) => T[] // 处理数据
  onSuccess?: () => void
  immediate?: boolean // 是否初始化执行
  rowKey?: string // 表格key
}
type useTableApi<T> = (p: Pagination) => Promise<
  {
    data: {
      records: T[]
      total: number
    }
  }
  | {
    rows: T[]
    total: number
  }
>

type Pagination = {
  page: number
  pageSize: number
}

// 分页hooks 搭配 el-pagination
export const usePagination = (
  callback = () => { },
  options = { defaultPageSize: 10 }
) => {
  const pagination = reactive({
    background: true,
    // 当前页
    page: 1,
    // 每页多少条数据
    pageSize: options.defaultPageSize,
    // 总数据
    total: 0,
    // 可切换页码数
    pageSizes: [10, 20, 30, 40, 50, 100],
    // 分页器布局
    layout: 'total,->, sizes, slot, prev, pager, next, jumper',
    onChange: (size: number) => {
      pagination.page = size
      callback && callback()
    },
    onPageSizeChange: (size: number) => {
      // pagination.page = 1 -- 这一行有个bug
      pagination.pageSize = size
      callback && callback()
    }
  })

  const changePage = pagination.onChange
  const changePageSize = pagination.onPageSizeChange
  const setTotal = (t: number) => {
    pagination.total = t
  }

  const { page, pageSize, total, pageSizes, layout } = toRefs(pagination)

  return {
    page,
    pageSize,
    total,
    pageSizes,
    layout,
    pagination,
    changePage,
    changePageSize,
    setTotal
  }
}

// 表格 hooks 搭配el-table使用
export const useTable = <T>(
  api: useTableApi<T>,
  options: useTableOptions<T>
) => {
  const { formatResult, onSuccess, immediate, rowKey } = options || {}

  const { pagination, setTotal } = usePagination(() => getTableData())

  const loading = ref(false)
  const tableData = ref<T[]>([]) as Ref<T[]>

  const getTableData = async () => {
    try {
      loading.value = true

      // TODO 参数 根据后端接口来
      const res = await api({
        page: pagination.page,
        pageSize: pagination.pageSize
      })
      let list = []
      let total = 0

      // // 网关那边
      // if ('data' in res) {
      //   list = res.data.list
      //   total = res.data.total
      // } else 

      if ('rows' in res) {
        // 线束业务这边
        list = (res.rows) ?? []
        total = res.total
      } else {
        // 苍穹外卖 records
        list = (res.data.records) ?? []
        total = res.data.total
      }

      tableData.value = formatResult ? formatResult(list) : list

      selectKeys.value = []
      // 等待表格dom渲染完毕
      await nextTick()

      setTotal(total)
      onSuccess && onSuccess()
    } catch (error) {
      console.log(error, 'error')
    } finally {
      loading.value = false
    }
  }

  // 刷新表格
  const refreshTable = async () => {
    console.log('refresh');

    pagination.page = 1
    getTableData()
  }

  // 是否初始化就执行
  const isImmediate = immediate ?? true;
  isImmediate && getTableData();

  // 多选
  const selectKeys = ref<T[]>([]) as Ref<T[]>

  const select = (rowKeys: T[]) => {
    selectKeys.value = unref(rowKeys)
  }

  // 全选
  const selectAll = (checked: T[]) => {
    selectKeys.value = checked ?? []
  }

  return {
    loading,
    tableData,
    pagination,
    selectKeys,
    refreshTable,
    getTableData,
    select,
    selectAll
  }
}